﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using StorageProject.DocumentGenerator.CSV;
using ProjectStorageLib.Project;
using CSVExportImport.Exceptions;

public partial class User_UploadProjects : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void m_btnUpload_Click(object s, EventArgs e)
    {
        if (m_fuCSVFile.HasFile)
        {
            String file;
            using (StreamReader reader = new StreamReader(m_fuCSVFile.FileContent))
            {
                file = reader.ReadToEnd();
            }
            file = file.Trim();
            using (StringReader sr = new StringReader(file))
            {
                CSSTemplate a = new CSSTemplate();

                ProjectsImporterManager res = null;
                try
                {
                    res = a.Import(sr, Security.GetCurrentUserID());
                }
                catch (CSVExportImportException)
                {
                    m_lblWarning.Text = "Parsing error";
                    return;
                }

                if (Validate(res))
                {
                    res.Save();
                }
            }
        }
    }

    public bool Validate(ProjectsImporterManager mngr)
    { 
        switch (mngr.Validate())
        {
            case ProjectsImporterManager.ValidationResult.OK:
                return true;
            case ProjectsImporterManager.ValidationResult.NameNotUnique:
                m_lblWarning.Text = "A project with the same name already exists!";
                return false;
            default:
                m_lblWarning.Text = "Error";
                return false;
        }
    }
}